
import re
import os
import sys
import shutil
import argparse

def get_args():
    parser = argparse.ArgumentParser(description=u'获取参数')
    parser.add_argument('-b', '--boot',
                        help=u'指定引导文件')
    parser.add_argument('-i', '--input',  
                        help=u'指定输入文件')
    parser.add_argument('-o', '--output',
                        help=u'指定输出文件，默认merge')
    parser.add_argument('-e', '--encode',
                        help=u'指定加密文件输出,默认uprade')
    parser.add_argument('-n', '--name',
                        help=u'指定固件版本文件')
    parser.add_argument('-p', '--path',
                        help=u'指定输出路径')
    args = parser.parse_args()
    # print(args)
    return args

def get_info(lines, head):
    info = ''
    for line in lines:
        m = re.match(head, line)
        if m :
            s = re.search(r'(\")(\S*)(\")', line)
            if s :
                info = s.groups()[1].replace('-', '_')
            break
    
    return info

def name_append(name, tail):
    if len(name) != 0:
        return name + '_' + tail

    return tail

def get_name(fname):
    import re
    # file_version = "VersionDefine.h"
    firmware_name = None

    if not fname:
        return None
    fname = fname.strip()
    if not os.path.isfile(fname):
        txt = "ERROR: File not found: %s" % fname
        print(txt) 
        return None

    with open(fname, 'r', encoding='utf-8', errors='ignore') as fin:
        lines = fin.readlines()
        ver_module = get_info(lines, '#define MODULE')
        ver_name = get_info(lines, '#define NAME')
        ver_date = get_info(lines, '#define DATE')
        ver_num = get_info(lines, '#define NUMBER')
        firmware_name = ver_module
        firmware_name = name_append(firmware_name, ver_name)
        firmware_name = name_append(firmware_name, ver_date)
        firmware_name = name_append(firmware_name, 'V' + ver_num)
        # for line in fin.readlines():
        #     m = re.match('#define FIRMWARE_VERSION', line)
        #     if m :
        #         s = re.search('(\")(\S*)(\")', line)
        #         if s :
        #             name = s.groups()[1].replace('-', '_')
        #             firmware_name = name
        #         break
    # print(firmware_name)
    return firmware_name.lstrip('_')

def main():
    args = get_args()
    # print(args)
    if not args.input:
        print('Input file is not specified')
        return 1

    if not args.boot:
        print('Boot file is not specified')
        return 1
    args.boot = args.boot.strip()
    if not os.path.isfile(args.boot):
        txt = "ERROR: File not found: %s" % args.boot   # that's required to get not-so-dumb result from 2to3 tool
        print(txt)
        return 2
    args.input = args.input.strip()
    if not os.path.isfile(args.input):
        txt = "ERROR: File not found: %s" % args.input   # that's required to get not-so-dumb result from 2to3 tool
        print(txt)
        return 2

    name = get_name(args.name)
    if name :
        if not args.output:
            args.output = name + '_merge.hex'
        if not args.encode:
            args.encode = name + '_upgrade.bin'

    if not args.output:
        args.output = 'merge.hex'
    else:
        args.output = args.output.strip()

    if not args.encode:
        args.encode = 'upgrade.bin'
    else:
        args.encode = args.encode.strip()

    if args.path :
        if not os.path.exists(args.path):
            os.makedirs(args.path)
        output_file = os.path.join(args.path, args.output)
        encode_file = os.path.join(args.path, args.encode)
    else:
        output_file = args.output
        encode_file = args.encode

    import hex86
    import hexmerge
    files = [args.boot, args.input]
    hexmerge.merge(files, output_file)
    hex86.encode(args.input, encode_file)
    # cmd_merge = 'python hexmerge.py -o {} {} {}'.format(args.output, args.boot, args.input)
    # cmd_encode = 'python hex86.py {} {}'.format(args.input, args.encode)
    # return os.system(cmd_merge + '&&' + cmd_encode)
    # os.system(cmd_encode)

if __name__ == '__main__' :
    #print(sys.getdefaultencoding())
    sys.exit(main())
        
    